<template>
	<view class="login-container">
		<!-- Logo部分 -->
		<view class="logo-section">
			<image class="logo" src="/static/logo.png" mode="aspectFit"></image>
			<text class="app-title">绿茵裁判通</text>
		</view>

		<!-- 登录卡片 -->
		<view class="login-card">
			<!-- 登录/注册切换部分 -->
			<view class="tab-section">
				<view class="tab-item active">
					<text>账号登录</text>
					<view class="active-line"></view>
				</view>
				<view class="tab-item register-tab" @click="goToRegister">
					<text>注册账号</text>
				</view>
			</view>
			
			<!-- 表单部分 -->
			<view class="form-section">
				<!-- 账号输入框 -->
				<view class="input-group">
					<view class="input-icon">
						<text class="icon-text">👤</text>
					</view>
					<input class="input-field" type="text" v-model="loginForm.account" placeholder="请输入用户名" @input="validateAccount" />
				</view>
				<view class="error-tip" v-if="errors.account">{{errors.account}}</view>
				
				<!-- 密码输入框 -->
				<view class="input-group">
					<view class="input-icon">
						<text class="icon-text">🔒</text>
					</view>
					<input class="input-field" :type="showPassword ? 'text' : 'password'" v-model="loginForm.password" placeholder="请输入密码" @input="validatePassword" />
					<view class="eye-icon" @click="togglePasswordVisibility">
						<text class="eye-text">{{showPassword ? '🙈' : '👁️'}}</text>
					</view>
				</view>
				<view class="error-tip" v-if="errors.password">{{errors.password}}</view>
				
				<!-- 忘记密码 -->
				<view class="password-options">
					<view class="remember-password">
						<checkbox :checked="loginForm.remember" @tap="loginForm.remember = !loginForm.remember" color="#1BAE76" style="transform:scale(0.8);" />
						<text @tap="loginForm.remember = !loginForm.remember">保存密码</text>
					</view>
					<view class="forget-password" @click="goToForgetPassword">
						<text>忘记密码</text>
					</view>
				</view>
			
				<!-- 登录按钮 -->
				<button class="login-btn" @click="handleLogin" :disabled="isSubmitting">登录</button>
			</view>
		</view>
		
		<!-- 其他登录方式 -->
		<view class="other-login-section">
			<view class="other-login-title">
				<view class="line"></view>
				<text>其他登录方式</text>
				<view class="line"></view>
			</view>
			
			<view class="other-login-icons">
				<view class="login-icon-item" @click="handleWechatLogin">
					<image class="wechat-icon" src="/static/images/wechat-icon.png" mode="aspectFit"></image>
					<text class="icon-label">微信登录</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getDeviceId } from '../../utils/device.js';
	import { setToken, clearToken, getToken } from '../../utils/tokenManager.js';
	
	export default {
		data() {
			return {
				loginForm: {
					account: '',
					password: '',
					loginType: 'username',
					remember: false
				},
				loginTypes: [
					{label: '用户名登录', value: 'username'},
					{label: '邮箱登录', value: 'email'}
				],
				showPassword: false,
				fromPage: '',
				errors: {
					account: '',
					password: ''
				},
				isSubmitting: false
			}
		},
		onLoad(options) {
			// 检查本地是否有保存的账号密码
			try {
				const savedLoginInfo = uni.getStorageSync('loginInfo');
				if (savedLoginInfo) {
					const loginInfo = JSON.parse(savedLoginInfo);
					this.loginForm.account = loginInfo.account;
					this.loginForm.password = loginInfo.password;
					this.loginForm.loginType = loginInfo.loginType;
					this.loginForm.remember = true;
					
					// 校验已保存的数据
					this.validateAccount();
				}
				
				// 记录来源页面
				if (options.from) {
					this.fromPage = decodeURIComponent(options.from);
				}
			} catch (e) {
				console.error('获取本地登录信息失败', e);
			}
		},
		methods: {
			// 切换密码显示
			togglePasswordVisibility() {
				this.showPassword = !this.showPassword;
			},
			
			// 记住密码变更
			onRememberChange(e) {
				this.loginForm.remember = e.detail.value;
			},
			
			// 切换登录类型
			changeLoginType(type) {
				this.loginForm.loginType = type;
				uni.showToast({
					title: type === 'username' ? '已切换到用户名登录' : '已切换到邮箱登录',
					icon: 'none'
				});
				this.validateAccount();
			},
			
			// 验证账号
			validateAccount() {
				this.errors.account = '';
				
				if (!this.loginForm.account) {
					this.errors.account = '请输入账号';
					return false;
				}
				
				if (this.loginForm.loginType === 'username') {
					// 用户名验证
					if (this.loginForm.account.length < 3 || this.loginForm.account.length > 20) {
						this.errors.account = '用户名长度需在3-20位之间';
						return false;
					}
					
					// 用户名格式验证 - 支持纯字母、纯数字、字母+数字
					const usernameReg = /^[a-zA-Z0-9]+$/;
					if (!usernameReg.test(this.loginForm.account)) {
						this.errors.account = '用户名只能包含字母和数字';
						return false;
					}
				}
				
				if (this.loginForm.loginType === 'email') {
					// 邮箱验证
					const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
					if (!emailReg.test(this.loginForm.account)) {
						this.errors.account = '请输入有效的邮箱';
						return false;
					}
				}
				
				return true;
			},
			
			// 验证密码
			validatePassword() {
				this.errors.password = '';
				
				if (!this.loginForm.password) {
					this.errors.password = '请输入密码';
					return false;
				}
				
				if (this.loginForm.password.length < 6) {
					this.errors.password = '密码长度不能少于6位';
					return false;
				}
				
				return true;
			},
			
			// 表单验证
			validateForm() {
				return this.validateAccount() && this.validatePassword();
			},
			
			// 跳转到注册页面
			goToRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				});
			},
			
			// 跳转到忘记密码页面
			goToForgetPassword() {
				uni.navigateTo({
					url: '/packageLogin/login/forget-password'
				});
			},
			
			// 处理常规登录
			async handleLogin() {
				if (!this.validateForm()) return;
				
				this.isSubmitting = true;
				
				uni.showLoading({
					title: '登录中...'
				});
				
				// 获取设备ID
				const deviceId = getDeviceId();
				
				try {
					// 使用云对象调用，根据登录类型映射字段
					const userService = uniCloud.importObject('user-service');
					let loginData = {
						password: this.loginForm.password,
						device_id: deviceId
					};
					
					// 根据登录类型设置对应字段
					if (this.loginForm.loginType === 'username') {
						loginData.account = this.loginForm.account;
						loginData.login_type = 'phone'; // 映射到phone类型，因为后端将用户名存储在phone字段
					} else if (this.loginForm.loginType === 'email') {
						loginData.account = this.loginForm.account;
						loginData.login_type = 'email';
					}
					
					const res = await userService.login(loginData);
					
					this.handleLoginResult(res);
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: '登录失败，请稍后重试',
						icon: 'none'
					});
					console.error('登录请求出错:', error);
				} finally {
					this.isSubmitting = false;
				}
			},
			
			// 处理微信登录
			handleWechatLogin() {
				this.isSubmitting = true;
				
				uni.showLoading({
					title: '微信登录中...'
				});
				
				// 获取微信登录code
				uni.login({
					provider: 'weixin',
					success: async (loginRes) => {
						if (loginRes.code) {
							try {
								// 使用云对象调用微信登录接口
								const userService = uniCloud.importObject('user-service');
								const res = await userService.wechatLogin({
										code: loginRes.code
								});
								
								this.handleLoginResult(res);
							} catch (error) {
								uni.hideLoading();
								uni.showToast({
									title: '微信登录失败，请稍后重试',
									icon: 'none'
								});
								console.error('微信登录请求出错:', error);
							} finally {
								this.isSubmitting = false;
							}
						} else {
							this.isSubmitting = false;
							uni.hideLoading();
							uni.showToast({
								title: '获取微信授权失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						this.isSubmitting = false;
						uni.hideLoading();
						uni.showToast({
							title: '微信登录失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 处理登录结果
			handleLoginResult(res) {
					if (res.code === 0) {
						// 登录成功
						uni.hideLoading();
						
						// 确保所有用户字段都已接收
						const userData = res.data;
						
						// 统一确保角色为数字类型，所有新用户默认为普通用户
						if (userData.role === undefined || userData.role === null) {
							userData.role = 0;
						}
						userData.role = parseInt(userData.role);
						
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});
						
						// 如果选择了记住密码，保存登录信息到本地
					if (this.loginForm.remember && this.loginForm.loginType !== 'wechat') {
							uni.setStorageSync('loginInfo', JSON.stringify({
								account: this.loginForm.account,
								password: this.loginForm.password,
								loginType: this.loginForm.loginType
							}));
						} else {
							uni.removeStorageSync('loginInfo');
						}
						
						// 使用tokenManager统一管理token
						setToken(userData.token, userData.expire_time);
						
						// 保存用户信息到本地存储
						uni.setStorageSync('userInfo', JSON.stringify(userData));
						
						// 根据来源页面决定跳转目标
					this.redirectAfterLogin();
				} else {
					uni.hideLoading();
					uni.showToast({
						title: res.message || '登录失败',
						icon: 'none'
					});
				}
			},
			
			// 登录后重定向
			redirectAfterLogin() {
				setTimeout(() => {
					if (this.fromPage === 'my') {
						uni.switchTab({
							url: '/pages/my/my'
						});
					} else if (this.fromPage === 'login/credential-upload' || this.fromPage === 'credential-upload') {
						// 重定向到新的证书上传页面
						uni.redirectTo({
							url: '/packageMy/my/credential-upload'
						});
					} else if (this.fromPage) {
						uni.redirectTo({
							url: decodeURIComponent(this.fromPage)
						});
					} else {
						uni.switchTab({
							url: '/pages/index/index'
						});
					}
				}, 1000);
			},
			async getLearningStatistics() {
				const token = getToken();
				if (!token) return;
				
				try {
					// 使用云对象调用
					const learningService = uniCloud.importObject('learning-service');
					const res = await learningService.getLearningStatistics({
						token: token
					});
					
					if (res.code === 0) {
						// 处理结果...
					}
				} catch (err) {
					console.error('获取学习统计失败', err);
				}
			}
		}
	}
</script>

<style>
	/* 引入字体图标 */
	@font-face {
		font-family: 'iconfont';
		src: url('data:font/ttf;base64,AAEAAAALAIAAAwAwR1NVQrD+s+0AAAE4AAAAQk9TLzI8fEg3AAABfAAAAFZjbWFwAX/4sgAAAeAAAAGGZ2x5ZjmZM0IAAANwAAABdGhlYWQayPQbAAAA4AAAADZoaGVhB94DhgAAALwAAAAkaG10eAwAAAAAAAHUAAAADGxvY2EANgA+AAADaAAAAAhtYXhwARIAMQAAARgAAAAgbmFtZT5U/n0AAASoAAACbXBvc3QpQgZPAAAHGAAAADkAAQAAA4D/gABcBAAAAAAABAAAAQAAAAAAAAAAAAAAAAAAAAMAAQAAAAEAAEsyh/dfDzz1AAsEAAAAAADZ1H/2AAAAANnUf/YAAP+ABAADgAAAAAgAAgAAAAAAAAABAAAAAwAkAAQAAAAAAAIAAAAKAAoAAAD/AAAAAAAAAAEAAAAKAB4ALAABREZMVAAIAAQAAAAAAAAAAQAAAAFsaWdhAAgAAAABAAAAAQAEAAQAAAABAAgAAQAGAAAAAQAAAAAAAQQAAZAABQAIAokCzAAAAI8CiQLMAAAB6wAyAQgAAAIABQMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUGZFZABA5gDmAQOA/4AAXAOAAIAAAAABAAAAAAAABAAAAAQAAAAEAAAAAAAABQAAAAMAAAAsAAAABAAAAV4AAQAAAAAAWAADAAEAAAAsAAMACgAAAV4ABAAsA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QMCAwQDAwIBAQP+AgG+/kIBvgsJGBkIAQECAgMCAwMBAQIBcgG+/kIBvgwZGwL+NQ0QAAAAABIA3gABAAAAAAAAABUAAAABAAAAAAABAAgAFQABAAAAAAACAAcAHQABAAAAAAADAAgAJAABAAAAAAAEAAgALAABAAAAAAAFAAsANAABAAAAAAAGAAgAPwABAAAAAAAKACsARwABAAAAAAALABMAcgADAAEECQAAACoAhQADAAEECQABABAArwADAAEECQACAA4AvwADAAEECQADABAAzQADAAEECQAEABAA3QADAAEECQAFABYA7QADAAEECQAGABABAwADAAEECQAKAFYBEwADAAEECQALACYBaQpDcmVhdGVkIGJ5IGljb25mb250Cmljb25mb250UmVndWxhcmljb25mb250aWNvbmZvbnRWZXJzaW9uIDEuMGljb25mb250R2VuZXJhdGVkIGJ5IHN2ZzJ0dGYgZnJvbSBGb250ZWxsbyBwcm9qZWN0Lmh0dHA6Ly9mb250ZWxsby5jb20ACgBDAHIAZQBhAHQAZQBkACAAYgB5ACAAaQBjAG8AbgBmAG8AbgB0AAoAaQBjAG8AbgBmAG8AbgB0AFIAZQBnAHUAbABhAHIAaQBjAG8AbgBmAG8AbgB0AGkAYwBvAG4AZgBvAG4AdABWAGUAcgBzAGkAbwBuACAAMQAuADAAaQBjAG8AbgBmAG8AbgB0AEcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAAcwB2AGcAMgB0AHQAZgAgAGYAcgBvAG0AIABGAG8AbgB0AGUAbABsAG8AIABwAHIAbwBqAGUAYwB0AC4AaAB0AHQAcAA6AC8ALwBmAG8AbgB0AGUAbABsAG8ALgBjAG8AbQAAAAACAAAAAAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMBAgEDAQQAB3Nob3VqaWEFc3VvZGEAAAAAAA==') format('truetype');
		font-weight: normal;
		font-style: normal;
	}

	.iconfont {
		font-family: "iconfont" !important;
		font-size: 24px;
		font-style: normal;
		color: #999;
	}
	
	.login-container {
		min-height: 100vh;
		background: linear-gradient(to bottom, #F8F8F8, #FFFFFF);
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20px;
	}
	
	/* Logo部分样式 */
	.logo-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 40px;
		margin-bottom: 30px;
	}
	
	.logo {
		width: 80px;
		height: 80px;
		border-radius: 15px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}
	
	.app-title {
		font-size: 18px;
		color: #1BAE76;
		font-weight: bold;
		margin-top: 10px;
	}
	
	/* 登录卡片样式 */
	.login-card {
		width: 90%;
		background-color: #FFFFFF;
		border-radius: 15px;
		padding: 20px;
		box-shadow: 0 5px 15px rgba(0,0,0,0.05);
		margin-bottom: 30px;
	}
	
	/* 标签切换样式 */
	.tab-section {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30px;
	}
	
	.tab-item {
		padding: 0 20px;
		height: 40px;
		line-height: 40px;
		font-size: 16px;
		color: #333;
		position: relative;
		text-align: center;
		flex: 1;
	}
	
	.tab-item.active {
		font-weight: bold;
	}
	
	.tab-item.register-tab {
		background-color: #FFFFFF;
		color: #1BAE76;
		border-radius: 20px;
		margin-left: 15px;
		border: 1px solid #1BAE76;
	}
	
	.active-line {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 20px;
		height: 3px;
		background-color: #1BAE76;
		border-radius: 2px;
	}
	
	/* 表单部分样式 */
	.form-section {
		width: 100%;
		display: flex;
		flex-direction: column;
	}
	
	.input-group {
		width: 100%;
		height: 50px;
		background-color: #F5F5F5;
		border-radius: 25px;
		margin-bottom: 15px;
		position: relative;
		display: flex;
		align-items: center;
	}
	
	.input-icon {
		padding: 0 10px 0 15px;
		display: flex;
		align-items: center;
	}
	
	.icon-text {
		font-size: 18px;
		color: #999;
	}
	
	.input-field {
		flex: 1;
		height: 100%;
		padding-right: 40px;
		font-size: 16px;
		background-color: transparent;
	}
	
	.eye-icon {
		position: absolute;
		right: 20px;
		width: 24px;
		height: 24px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.eye-text {
		font-size: 16px;
		color: #999;
	}
	
	.error-tip {
		font-size: 12px;
		color: #FF5252;
		margin-top: -10px;
		margin-bottom: 10px;
		padding-left: 20px;
	}
	
	.password-options {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		padding: 0 5px;
	}
	
	.remember-password {
		display: flex;
		align-items: center;
	}
	
	.remember-password text {
		color: #1BAE76;
		font-size: 14px;
		margin-left: 5px;
	}
	
	.forget-password {
		display: flex;
		align-items: center;
	}
	
	.forget-password text {
		color: #1BAE76;
		font-size: 14px;
	}
	
	.login-btn {
		width: 90%;
		height: 50px;
		line-height: 50px;
		border-radius: 25px;
		background: linear-gradient(to right, #1BAE76, #3CD6A0);
		color: white;
		font-size: 16px;
		font-weight: bold;
		border: none;
		margin-top: 10px;
		text-align: center;
		padding: 0;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.login-btn:active {
		opacity: 0.8;
	}
	
	/* 其他登录方式 */
	.other-login-section {
		width: 90%;
		position: absolute;
		bottom: 50px;
	}
	
	.other-login-title {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 20px;
	}
	
	.line {
		width: 80px;
		height: 1px;
		background-color: #DDD;
	}
	
	.other-login-title text {
		font-size: 14px;
		color: #999;
		margin: 0 10px;
	}
	
	.other-login-icons {
		display: flex;
		justify-content: center;
	}
	
	.login-icon-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #F5F5F5;
		border-radius: 15px;
		padding: 15px 20px;
		margin: 0 15px;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}
	
	.login-icon-item:active {
		opacity: 0.8;
		transform: scale(0.95);
	}
	
	.wechat-icon {
		width: 24px;
		height: 24px;
		margin-bottom: 5px;
	}
	
	.icon-label {
		font-size: 12px;
		color: #666;
	}
</style> 